<template>
  <div class="scriptManage">
    <!-- 下方 -->
    <div class="scriptManage_bottom" v-loading="loading" element-loading-text="加载中..."
      element-loading-spinner="el-icon-loading" element-loading-background="rgba(200, 200, 200, 0.7)">
      <div class="scr_list">
        <!-- 左上角的脚本列表 -->
        <!-- <div class="scr_list_top"> -->
        <!-- 列表头的操作 -->
        <el-button size="mini" style=" float: left; margin-left: 0.1rem; margin-top: 0.5rem;" type="primary" title="返回列表"
          @click="goBack">返回脚本列表</el-button>
        <el-button size="mini" style=" float: right; margin-right: 0.1rem; margin-top: 0.5rem;" type="warning"
          title="重新读取" @click="getScriptAll">重新读取</el-button><br />
        <div class="headerTop">
          <span style="font-weight: 600;">脚本列表</span>
          <el-button size="mini" type="plain" icon="el-icon-plus"
            style="float: right; vertical-align: middle; margin-top: 0.1rem; padding: 6px 8px; "
            @click="addScript">添加</el-button>
        </div>
        <!-- 列表 -->
        <div class="top_list">
          <div v-for="(item, index) in scrList" :key="item.value" :title="item.script_name" :class="[
            'oneScriptList',
            { selectedItem: selectedIndex === index }
          ]">
            <div @click="selectItem(index, item)" style="width: 90%; text-align: left">
              {{ item.script_name }}
            </div>
            <div style="flex:1;text-align:right">
              <i style="color: #f56c6c" class="el-icon-delete iconBtn" @click="() => sureDeleteScript(index, item)">
              </i>
            </div>
          </div>
        </div>
        <!-- </div> -->
        <!-- 三个按钮 -->
        <div class="left_btn_group">
          <el-button size="mini" type="primary" v-if="isOn" title="保存" @click="save()">保 存</el-button>
          <el-button size="mini" type="primary" v-if="isOn" title="下发" @click="Distribute()">下 发</el-button>

          <el-button size="mini" type="primary" v-if="isOn" title="保存并下发" @click="saveAndDistribute">保存并下发</el-button>
        </div>
      </div>

      <!-- 中间信息 -->
      <div class="scr_group">
        <div class="btn_group_list">
          <!-- <div v-if="look == 1" class="top_btn" style="background-color: green;">
                        添 加 脚 本
                    </div>
                    <div v-if="look == 2" class="top_btn" style="background-color: blue;">
                        编 辑 脚 本
                    </div> -->
          名称:
          <el-input class="inpu" v-model="scriptAlloca.scrName" placeholder="脚本名称"
            :disabled="look === 2"></el-input>&nbsp;&nbsp;&nbsp; 类型:
          <el-select v-model="scriptAlloca.type" class="inpu" :disabled="look === 2">
            <el-option v-for="item in workType" :key="item.value" :value="item.value" :label="item.label"></el-option>
          </el-select>&nbsp;&nbsp;&nbsp; 循环间隔:
          <el-input type="number" class="inpu" v-model="scriptAlloca.timeInterval" :disabled="look === 2"></el-input>
          S
        </div>
        <div class="btn_group">
          <el-menu :default-active="activeIndex" text-color="#000" active-text-color="#000" class="el-menu-demo"
            mode="horizontal" @select="handleSelect" unique-opened>
            <!-- <el-menu-item index="1">处理中心</el-menu-item> -->
            <!-- 1.语句 -->
            <el-submenu index="1" title="语句" :disabled="look === 2">
              <template slot="title">IF</template>
              <el-menu-item index="1-1" class="itemMenu">IF THEN ENDIF</el-menu-item>
              <el-menu-item index="1-2" class="itemMenu">IF THEN ELSE ENDIF</el-menu-item>
            </el-submenu>
            <!-- 2.逻辑运算符 -->
            <el-submenu index="2" title="逻辑运算符" :disabled="look === 2">
              <template slot="title">OR</template>
              <el-menu-item index="2-1" class="itemMenu">and</el-menu-item>
              <el-menu-item index="2-2" class="itemMenu">or</el-menu-item>
              <el-menu-item index="2-3" class="itemMenu">not</el-menu-item>
            </el-submenu>
            <!-- 3.算数运算符 -->
            <el-submenu index="3" title="算数运算符" :disabled="look === 2">
              <template slot="title">+</template>
              <el-menu-item index="3-1" class="itemMenu">+</el-menu-item>
              <el-menu-item index="3-2" class="itemMenu">-</el-menu-item>
              <el-menu-item index="3-3" class="itemMenu">*</el-menu-item>
              <el-menu-item index="3-4" class="itemMenu">/</el-menu-item>
              <el-menu-item index="3-5" class="itemMenu">%</el-menu-item>
            </el-submenu>
            <!-- 4.比较运算符 -->
            <el-submenu index="4" title="比较运算符" :disabled="look === 2">
              <template slot="title">></template>
              <el-menu-item index="4-1" class="itemMenu">=</el-menu-item>
              <el-menu-item index="4-2" class="itemMenu">==</el-menu-item>
              <el-menu-item index="4-3" class="itemMenu">&lt;</el-menu-item>
              <el-menu-item index="4-4" class="itemMenu">&gt;</el-menu-item>
              <el-menu-item index="4-5" class="itemMenu">&le;</el-menu-item>
              <el-menu-item index="4-6" class="itemMenu"> &ge;</el-menu-item>
              <el-menu-item index="4-7" class="itemMenu">!=</el-menu-item>
            </el-submenu>
            <!-- 6.系统变量 -->
            <el-submenu index="6" title="系统变量" :disabled="look === 2">
              <template slot="title">Tv</template>
              <el-submenu index="6-1">
                <template slot="title">时间</template>
                <el-menu-item index="6-1-1" class="itemMenu">年</el-menu-item>
                <el-menu-item index="6-1-2" class="itemMenu">月</el-menu-item>
                <el-menu-item index="6-1-3" class="itemMenu">日</el-menu-item>
                <el-menu-item index="6-1-4" class="itemMenu">时</el-menu-item>
                <el-menu-item index="6-1-5" class="itemMenu">分</el-menu-item>
                <el-menu-item index="6-1-6" class="itemMenu">秒</el-menu-item>
                <el-menu-item index="6-1-7" class="itemMenu">星期</el-menu-item>
                <el-menu-item index="6-1-8" class="itemMenu">日分</el-menu-item>
                <el-menu-item index="6-1-9" class="itemMenu">时分</el-menu-item>
              </el-submenu>
              <el-submenu index="6-2">
                <template slot="title">定时器</template>
                <el-menu-item index="6-2-1" class="itemMenu">Tv</el-menu-item>
                <el-menu-item index="6-2-2" class="itemMenu">Ts</el-menu-item>
              </el-submenu>
              <el-submenu index="6-3">
                <template slot="title">内部变量</template>
                <el-menu-item index="6-3-1" class="itemMenu">X</el-menu-item>
                <el-menu-item index="6-3-2" class="itemMenu">Y</el-menu-item>
                <el-menu-item index="6-3-3" class="itemMenu">M</el-menu-item>
                <el-menu-item index="6-3-4" class="itemMenu">S</el-menu-item>
                <el-menu-item index="6-3-5" class="itemMenu">D</el-menu-item>
                <el-menu-item index="6-3-6" class="itemMenu">DL</el-menu-item>
                <el-menu-item index="6-3-7" class="itemMenu">DU</el-menu-item>
                <el-menu-item index="6-3-8" class="itemMenu">DUL</el-menu-item>
                <el-menu-item index="6-3-9" class="itemMenu">DF</el-menu-item>
                <el-menu-item index="6-3-10" class="itemMenu">DD</el-menu-item>
              </el-submenu>
              <el-submenu index="6-4">
                <template slot="title">网络</template>
                <el-menu-item index="6-4-1" class="itemMenu">NetSts</el-menu-item>
                <el-menu-item index="6-4-2" class="itemMenu">Rssi</el-menu-item>
              </el-submenu>
            </el-submenu>
            <!-- 7.Fun -->
            <el-submenu index="7" title="常用功能" :disabled="look === 2">
              <template slot="title">Fun</template>
              <el-menu-item index="7-1" class="itemMenu">循环启停</el-menu-item>
              <el-menu-item index="7-2" class="itemMenu">延时启动</el-menu-item>
              <el-menu-item index="7-3" class="itemMenu">延时停止</el-menu-item>
            </el-submenu>
            <!-- 5.注释 -->
            <el-menu-item index="5" title="注释符" class="oneMenu" :disabled="look === 2">//</el-menu-item>
          </el-menu>
        </div>
        <div class="code-edit">
          <!-- <div class="top-title">公式</div> -->
          <codemirror ref="codeEditor" v-model="scriptAlloca.content" :options="cmOptions" @input="codeMirrorChange">
          </codemirror>
        </div>
        <el-button size="mini" v-if="look == 1" class="save_btn" type="success" @click="sureScript">确 认 添 加</el-button>
        <el-button size="mini" v-if="look == 2" class="save_btn" type="primary" @click="sureScript">编 辑</el-button>
        <el-button size="mini" v-if="look == 3" class="save_btn" type="success" @click="sureScript">确 认 编 辑</el-button>
      </div>
      <!-- 右侧列表 -->
      <div class="point_group">
        <h5>变量列表</h5>
        <div class="sensorTree">
          <el-input style="width:98%;display:block;margin:0 auto;" :disabled="look === 2" placeholder="输入关键字进行过滤"
            v-model="filterText">
          </el-input>
          <el-tree style="margin-top:0.1rem;" class="filter-tree" :data="sensorTree" :indent="30"
            :render-content="renderContent" @node-click="getSensorString" default-expand-all
            :filter-node-method="filterNode" ref="tree">
          </el-tree>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { codemirror } from "vue-codemirror";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/idea.css";

export default {
  components: { codemirror },
  data() {
    return {
      close: false,
      // 整体的数据
      // deviceData : JSON.parse(localStorage.getItem('deviceData')),

      // 脚本语言列表
      scrList: [],
      selectedIndex: -1,
      // addForm: {
      //     script_list_name: '',
      //     script_type: '',
      //     interval: '',

      // },
      scriptAddVisible: false,

      scriptAlloca: {
        scrName: "",
        type: 1,
        timeInterval: 0,
        content: ""
      },
      workType: [
        { value: 0, label: "启动时运行一次" },
        { value: 1, label: "循环运行" }
      ],
      cmOptions: {
        // 语言及语法模式
        mode: "text/javascript",
        // 主题
        theme: "idea",
        // 显示函数
        line: true,
        lineNumbers: true,
        // 软换行
        lineWrapping: true,
        // tab宽度
        tabSize: 4,
        readOnly: false,
        // 显示光标
        showCursorWhenSelecting: true,
        // 剪切当前行
        lineWiseCopyCut: true,
        autofocus: true
      },
      lang: "javascript",

      activeIndex: "",
      // 右边变量
      filterText: "",
      sensorTree: [],
      // 按钮的文字
      look: 1,
      // 编辑时候的id临时储存
      editId: null,
      loading: true
    };
  },
  props: ["deviceData", "isOn", "isRead"],
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  computed: {
    editor() {
      return this.$refs.codeEditor.codemirror;
    }
  },
  mounted() {
    // this.deviceData = JSON.parse(localStorage.getItem('deviceData'));
    var that = this;
    // setTimeout(() => {
    that.getScriptAll();
    this.focus(this.scriptAlloca.content);
    this.autoMarkText();
    this.getSlaveSensorTree();

    // }, 1000);
    // 查询脚本信息
  },
  methods: {
    // 查询脚本信息
    getScriptAll() {
      this.loading = true;
      var that = this;
      (this.scrList = []),
        this.$http({
          method: "post",
          url: "api/equip/readScript",
          data: {
            id: this.deviceData.id
          }
        })
          .then(res => {
            if (res && res.data.result == "success") {
              that.scrList = res.data.data;
              this.moren();
              that.loading = false;
            } else {
              that.loading = false;
            }
          })
          .catch(error => {
            that.loading = false;
            console.log(error);
          });
    },
    //默认选中第一个
    moren() {
      var that = this;
      let Base64 = require("js-base64").Base64;
      if (this.scrList.length > 0) {
        this.selectedIndex = 0;
        (this.scriptAlloca = {
          scrName: this.scrList[0].script_name,
          type: this.scrList[0].script_type,
          timeInterval: this.scrList[0].interval,
          content: Base64.decode(this.scrList[0].content)
        }),
          (that.look = 2);
        that.cmOptions.readOnly = true;
      }
    },
    // 添加脚本列表项目
    addScript() {
      this.look = 1;
      (this.selectedIndex = -1),
        (this.cmOptions.readOnly = false),
        (this.scriptAlloca = {
          scrName: "",
          type: 0,
          timeInterval: 0,
          content: ""
        });
    },
    // 确定添加
    sureScript() {
      let Base64 = require("js-base64").Base64;
      var that = this;
      if (this.look == 1) {
        if (
          this.scriptAlloca.scrName == "" ||
          this.scriptAlloca.content == ""
        ) {
          this.$message({
            message: "请完善内容",
            type: "error",
            center: true
          });
          return;
        } else {
          // 点击了新增
          const temporary = {
            script_name: this.scriptAlloca.scrName,
            script_type: this.scriptAlloca.type,
            interval: this.scriptAlloca.timeInterval,
            content: Base64.encode(this.scriptAlloca.content)
          };
          this.scrList.push(temporary);
          this.$message({
            message: "添加脚本成功!",
            type: "success",
            center: true
          });
          // this.scriptAlloca = {
          //     scrName: '',
          //     type: 0,
          //     timeInterval: 0,
          //     content: ''
          // }
          setTimeout(() => {
            that.selectedIndex = that.scrList.length - 1;
            let l = that.scrList.length - 1;
            (that.scriptAlloca = {
              scrName: that.scrList[l].script_name,
              type: that.scrList[l].script_type,
              timeInterval: that.scrList[l].interval,
              content: Base64.decode(that.scrList[l].content)
            }),
              (that.look = 2);
            that.cmOptions.readOnly = true;
          }, 400);
        }
      } else if (this.look === 2) {
        // 解开封印
        this.look = 3;
        this.cmOptions.readOnly = false;
      } else if (this.look === 3) {
        // 点击后是编辑
        if (
          this.scriptAlloca.scrName == "" ||
          this.scriptAlloca.content == ""
        ) {
          this.$message({
            message: "请完善内容",
            type: "error",
            center: true
          });
          return;
        } else {
          const temporary = {
            script_name: this.scriptAlloca.scrName,
            script_type: this.scriptAlloca.type,
            interval: this.scriptAlloca.timeInterval,
            content: Base64.encode(this.scriptAlloca.content)
          };
          this.look = 2;
          this.cmOptions.readOnly = true;
          this.scrList[this.selectedIndex] = temporary;
          this.$message({
            message: "修改脚本成功!",
            type: "success",
            center: true
          });
        }

        // this.$http({
        //     method: 'post',
        //     url: 'api/script/update',
        //     data: {
        //         equip_id: this.deviceData.id,
        //         id: this.editId,
        //         script_name: this.scriptAlloca.scrName,
        //         script_type: this.scriptAlloca.type,
        //         interval: this.scriptAlloca.timeInterval,
        //         content: this.scriptAlloca.content,
        //     }

        // }).then(res => {
        //     if (res && res.data.result == "success") {
        //         this.$message({
        //             message: '编辑脚本成功!',
        //             type: 'success',
        //             center: true
        //         });
        //         this.look = 2
        //         this.cmOptions.readOnly = true
        //         this.getScriptAll()
        //     }
        // }).catch(error => {
        //     console.log(error);
        // });
      }
    },
    // 点击了某一个项目
    selectItem(index, item) {
      let Base64 = require("js-base64").Base64;
      this.selectedIndex = index;
      // this.$http({
      //     method: 'post',
      //     url: 'api/script/info',
      //     data: {
      //         id: item.id
      //     }

      // }).then(res => {
      //     if (res && res.data.result == "success") {
      this.look = 2;
      this.cmOptions.readOnly = true;
      // console.log('脚本详情', res);
      this.scriptAlloca.scrName = item.script_name;
      this.scriptAlloca.type = item.script_type;
      this.scriptAlloca.timeInterval = item.interval;
      this.scriptAlloca.content = Base64.decode(item.content);

      //     }
      // }).catch(error => {
      //     console.log(error);
      // });
    },
    // 删除脚本项目
    sureDeleteScript(index, item) {
      // console.log(index, item);
      var that = this;
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(() => {
          this.scrList.splice(index, 1);

          if (index == this.selectedIndex) {
            // 删除的是当前选中的   包含了最后一个脚本的时候  删除后的效果
            that.scriptAlloca = {
              scrName: "",
              type: 0,
              timeInterval: 0,
              content: ""
            };
            setTimeout(() => {
              that.moren();
            }, 300);
          } else {
            // 删除的不是当前选中的行
            // 删除的是上面的
            if (index < this.selectedIndex) {
              this.selectedIndex -= 1;
            }
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 保存
    save() {
      var that = this;
      that.loading = true;
      this.$http({
        method: "post",
        url: "api/equip/saveScript",
        data: {
          id: this.deviceData.id,
          scripts: this.scrList
        }
      })
        .then(res => {
          if (res && res.data.result == "success") {
            // console.log('保存脚本', res);

            that.loading = false;
            this.$emit("goSet", false);
          } else {
            that.loading = false;
          }
        })
        .catch(error => {
          console.log(error);
          that.loading = false;
        });
    },
    Distribute() {
      var that = this;
      that.loading = true;
      this.$http({
        method: "post",
        url: "api/equip/writeScript",
        data: {
          id: this.deviceData.id,
          scripts: this.scrList
        }
      })
        .then(res => {
          if (res && res.data.result == "success") {
            // console.log('下发脚本', res);

            that.loading = false;
            this.$emit("goSet", false);
          } else {
            that.loading = false;
          }
        })
        .catch(error => {
          that.loading = false;
          console.log(error);
        });
    },
    // 保存并且下发

    saveAndDistribute() {
      var that = this;
      that.loading = true;
      this.$http({
        method: "post",
        url: "api/equip/saveWriteScript",
        data: {
          id: this.deviceData.id,
          scripts: this.scrList
        }
      })
        .then(res => {
          if (res && res.data.result == "success") {
            // console.log('保存下发脚本', res);

            that.loading = false;
            this.$emit("goSet", false);
          } else {
            that.loading = false;
          }
        })
        .catch(error => {
          console.log(error);
          that.loading = false;
        });
    },

    handleChange(value) {
      console.log(value);
    },
    handleSelect(key, keyPath) {
      // console.log(key, keyPath);
      // 语句
      if (keyPath[0] == "1") {
        switch (keyPath[1]) {
          case "1-1":
            this.insertContent(" if    then  \n\n  endif", "");
            break;
          case "1-2":
            this.insertContent(" if    then  \n\n  else \n\n  endif", "string");
            break;
          default:
          // 处理其他情况，如果有需要的话
        }
      }
      // 逻辑运算
      if (keyPath[0] == "2") {
        switch (keyPath[1]) {
          case "2-1":
            this.insertContent("and ", "string");
            break;
          case "2-2":
            this.insertContent("or ", "string");
            break;
          case "2-3":
            this.insertContent("not ", "string");
            break;
        }
      }
      // 算数运算
      if (keyPath[0] == "3") {
        switch (keyPath[1]) {
          case "3-1":
            this.insertContent("+ ", "count");
            break;
          case "3-2":
            this.insertContent("- ", "count");
            break;
          case "3-3":
            this.insertContent("* ", "count");
            break;
          case "3-4":
            this.insertContent("/ ", "count");
            break;
          case "3-5":
            this.insertContent("% ", "count");
            break;
        }
      }
      // 比较运算
      if (keyPath[0] == "4") {
        switch (keyPath[1]) {
          case "4-1":
            this.insertContent("= ", "count");
            break;
          case "4-2":
            this.insertContent("== ", "count");
            break;
          case "4-3":
            this.insertContent("< ", "count");
            break;
          case "4-4":
            this.insertContent("> ", "count");
            break;
          case "4-5":
            this.insertContent("<= ", "count");
            break;
          case "4-6":
            this.insertContent(">= ", "count");
            break;
          case "4-7":
            this.insertContent("!= ", "count");
            break;
        }
      }
      // 注释
      if (keyPath[0] == "5") {
        this.insertContent("// ", "annot");
      }
      // 系统变量
      if (keyPath[0] == "6") {
        switch (key) {
          case "6-1-1":
            this.insertContent("$Year ", "");
            break;
          case "6-1-2":
            this.insertContent("$Month ", "");
            break;
          case "6-1-3":
            this.insertContent("$Day ", "");
            break;
          case "6-1-4":
            this.insertContent("$Hour ", "");
            break;
          case "6-1-5":
            this.insertContent("$Min ", "");
            break;
          case "6-1-6":
            this.insertContent("$Sec ", "");
            break;
          case "6-1-7":
            this.insertContent("$Week ", "");
            break;
          case "6-1-8":
            this.insertContent("$DMin ", "");
            break;
          case "6-1-9":
            this.insertContent("$HMin ", "");
            break;
          case "6-2-1":
            this.insertContent("$Tv1 ", "");
            break;
          case "6-2-2":
            this.insertContent("$Ts1 ", "");
            break;

          case "6-3-1":
            this.insertContent("$X ", "");
            break;
          case "6-3-2":
            this.insertContent("$Y ", "");
            break;
          case "6-3-3":
            this.insertContent("$M ", "");
            break;
          case "6-3-4":
            this.insertContent("$S ", "");
            break;
          case "6-3-5":
            this.insertContent("$D ", "");
            break;
          case "6-3-6":
            this.insertContent("$DL ", "");
            break;
          case "6-3-7":
            this.insertContent("$DU ", "");
            break;
          case "6-3-8":
            this.insertContent("$DUL ", "");
            break;
          case "6-3-9":
            this.insertContent("$DF ", "");
            break;
          case "6-3-10":
            this.insertContent("$DD ", "");
            break;

          case "6-4-1":
            this.insertContent("$NetSts@sys ", "");
            break;
          case "6-4-2":
            this.insertContent("$Rssi@sys ", "");
            break;
        }
      }
      // 比较运算
      if (keyPath[0] == "7") {
        switch (keyPath[1]) {
          case "7-1":
            this.insertContent(
              "//循环开30s,关30s\nif $M0 ==1 and $Ts2 ==0 then\n$Tv1 =30\nelse\n$Tv1 =0\nendif\nif $Ts1 ==1 then\n$Tv2 =30\nelse\n$Tv2 =0\nendif\nif $M0 ==1 and $Ts1 ==0 then\n$M1 =1\nelse\n$M1 =0\nendif\n",
              "common"
            );
            break;
          case "7-2":
            this.insertContent(
              "//延时20s启动\nif $M10 ==1 then\n$Tv4 =20\nelse\n$Tv4 =0\nendif\nif $Ts4 ==1 then\n$M11 =1\nelse\n$M11 =0\nendif\n",
              "common"
            );
            break;
          case "7-3":
            this.insertContent(
              "//延时20s停止\nif $M20 ==1 then\n$M21=1\nendif\nif $M20 ==0 then\n$Tv3 =20\nelse\n$Tv3 =0\nendif\nif $M20 ==0 and $Ts3 ==1 then\n$M21 =0\nendif\n",
              "common"
            );
            break;
        }
      }
    },
    codeMirrorChange() {
      //获取 editor 的内容
      // console.log("content1: " + this.scriptAlloca.content);
      // console.log("content2: " + JSON.stringify(this.editor.getValue()));
      this.autoMark();
      // this.autoMarkText()
      // let allText = JSON.stringify(this.editor.getValue())
    },
    addFormula(content, type) {
      this.insertContent(content, type);
    },
    /**
     * editor 中的对内容进行处理
     * @param value
     * @param type variable | func，variable为表单变量，需标记，func 为函数，也需要做标记
     */
    // 点击新增预设的内容
    insertContent(value, type) {
      const from = this.editor.getCursor();
      if (type === "variable") {
        this.editor.replaceSelection(value);
        const to = this.editor.getCursor();
        this.markText(from, to, value, "cm-field");
      } else if (type === "func") {
        this.editor.replaceSelection(`${value}()`);
        const to = this.editor.getCursor();
        this.markText(from, { line: to.line, ch: to.ch - 4 }, value, "cm-func");
        this.editor.setCursor({ line: to.line, ch: to.ch - 1 });
      } else if (type === "end") {
        this.editor.replaceSelection(value, from);
      } else if (type === "count") {
        this.editor.replaceSelection(value);
        const to = this.editor.getCursor();
        this.markText(from, to, value, "cm-count");
      } else if (type === "annot" || type === "common") {
        this.editor.replaceSelection(value);
        const to = this.editor.getCursor();
        this.markText(from, to, value, "cm-green");
      } else if (typeof value === "string") {
        this.editor.replaceSelection(value);
      } else {
        this.editor.replaceSelection(value);
      }
      this.editor.focus();
    },
    autoMarkText() {
      if (this.scriptAlloca.content) {
        this.autoMark(this.scriptAlloca.content);
        this.focus(this.scriptAlloca.content);
      }
    },
    focus(value) {
      this.editor.setCursor({
        line: 0,
        ch: value ? value.length : 0
      });
      this.editor.focus();
    },
    markText(from, to, label, className) {
      if (className === void 0) {
        className = "cm-func";
      }
      let text = document.createElement("span");
      text.className = className;
      text.innerText = label;
      this.editor.markText(from, to, {
        atomic: true,
        replacedWith: text
      });
    },
    /**
     * 解析 editor 的内容，分别对表单变量和函数进行标记
     */
    autoMark() {
      const editor = this.editor;
      const lines = editor.lineCount();
      for (let line = 0; line < lines; line++) {
        const content = editor.getLine(line);
        // console.log('shaixuan', content)
        // 标记函数调用,匹配一个或多个连续的大写字母，后面可以有任意数量的空白字符，再紧跟一个左括号
        // content.replace(/([A-Z]+)\s*\(/g, (_, func, pos) => {
        //   this.markText(
        //     { line: line, ch: pos },
        //     { line: line, ch: pos + func.length },
        //     func,
        //     "cm-func"
        //   );
        //   return _;
        // });
        // 标记表单变量,这应该是动态获取，自行替换即可
        // let vars = ["表单", "表单1", "表单11", "表单12"];
        // vars.forEach(v => {
        //   let from = 0;
        //   let idx = -1;
        //   while (~(idx = content.indexOf(v, from))) {
        //     this.markText(
        //       { line: line, ch: idx },
        //       { line: line, ch: idx + v.length },
        //       v,
        //       "cm-field"
        //     );
        //     from = idx + v.length;
        //   }
        // });
        // 标记算数运算符
        let vars1 = ["+", "-", "*", "/", "%", "=", "=="];
        vars1.forEach(v => {
          let from = 0;
          let idx = -1;
          while (~(idx = content.indexOf(v, from))) {
            for (let i = 0; i < v.length; i++) {
              this.markText(
                { line: line, ch: idx + i },
                { line: line, ch: idx + i + 1 },
                v.charAt(i),
                "cm-count"
              );
            }
            from = idx + v.length;
          }
        });
        // 注释标识
        let startIndex = content.indexOf("//");
        while (startIndex !== -1) {
          let endIndex = content.indexOf("\n", startIndex); // 寻找从 startIndex 开始第一个 "\n" 的位置
          if (endIndex === -1) {
            endIndex = content.length; // 如果未找到 "\n",将结束位置设为文本末尾
          }

          let textToHighlight = content.substring(startIndex, endIndex); // 获取以 "//" 开头到 结束的文本
          // console.log("Found: " + textToHighlight);

          // 在这里调用 markText 函数，给找到的文本添加自定义的类名
          this.markText(
            { line: line, ch: startIndex },
            { line: line, ch: endIndex },
            textToHighlight,
            "cm-green"
          );

          startIndex = content.indexOf("//", endIndex); // 继续寻找下一个以 "//" 开头的位置
        }

        // 大小括号变成暗红色
        let vars3 = ["(", ")", "{", "}"];
        vars3.forEach(v => {
          let from = 0;
          let idx = -1;
          while (~(idx = content.indexOf(v, from))) {
            this.markText(
              { line: line, ch: idx },
              { line: line, ch: idx + v.length },
              v,
              "cm-darkRed"
            );
            from = idx + v.length;
          }
        });
        // 数字以及特殊英文变蓝色
        let vars4 = [
          "0",
          "1",
          "2",
          "3",
          "4",
          "5",
          "6",
          "7",
          "8",
          "9",
          "if",
          "and",
          "then",
          "endif",
          "else",
          "or",
          "not"
        ];
        vars4.forEach(v => {
          let from = 0;
          let idx = -1;
          while (~(idx = content.indexOf(v, from))) {
            for (let i = 0; i < v.length; i++) {
              this.markText(
                { line: line, ch: idx + i },
                { line: line, ch: idx + i + 1 },
                v.charAt(i),
                "cm-blue"
              );
            }
            from = idx + v.length;
          }
        });
      }
    },

    //获取设备的从机变量树
    getSlaveSensorTree(id = this.deviceData.id) {
      var that = this;
      this.sensorTree = [];
      this.$http({
        method: "post",
        url: "api/equip/sensorTree", //该接口已去掉虚拟变量
        data: {
          id: id
        }
      })
        .then(res => {
          if (res && res.data.result == "success") {
            if (res.data.data.length) {
              console.log("res.data.data", res.data.data[0]);
              var z = res.data.data;
              for (let i = 0; i < z[0].children.length; i++) {
                const s = z[0].children[i];
                for (let index = 0; index < s.children.length; index++) {
                  z[0].children[i].children[index].label =
                    z[0].children[i].children[index].label +
                    " " +
                    "(" +
                    "$" +
                    z[0].children[i].children[index].value_key +
                    "@" +
                    z[0].children[i].children[index].slave_no +
                    ")";
                }
              }
              setTimeout(() => {
                that.sensorTree = Array.from(z);
                that.$forceUpdate();
              }, 200);
            }
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 给空的前面加一个空格
    renderContent(h, { node, data }) {
      // console.log('33', h, { node, data })
      if (data.children && data.children.length === 0) {
        if (!data.label.startsWith("\u00A0\u00A0\u00A0\u00A0")) {
          data.label = "\u00A0\u00A0\u00A0\u00A0" + data.label; // 在label前添加一个占位符，如果已有占位符则不重复添加
        }
      }

      return h(
        "span",
        // {
        //     style: { display: 'inline-flex', alignItems: 'center' }
        // },
        [data.label]
      );
    },
    // 禁用tree

    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    getSensorString(data, node, ele) {
      // console.log(data);
      if (this.look === 2) {
        return;
      }
      if (!data.value_key) {
        return;
      }
      let symbol = "-";
      if (data.label.includes(symbol)) {
        this.$message({
          message: "变量中不能含有'-''",
          type: "error",
          center: true
        });
        return;
      }
      this.sibling = ele.$el.parentNode.children;
      // for(let i=0;i<this.sibling.length;i++){
      // 	  this.sibling[i].style.color="#333";
      // }
      // ele.$el.style.color = "#409eff";
      let str = "$" + data.value_key + "@" + data.slave_no + " ";
      // console.log('strrrrrrrr', str)
      this.insertContent(str, "string");
      // if (this.oper == "add") {
      // this.addForm.formula = (this.addForm.formula + '  ' + str).trim();
      // } else if (this.oper == "edit") {
      //     this.editForm.formula = (this.editForm.formula + '  ' + str).trim();
      // }
    },

    goBack() {
      this.$emit("goSet", false);
      // this.$router.push({
      //           name: 'deviceSet',
      //           path: '/deviceSet'
      //     });
    }
  }
};
</script>

<style lang="less" scoped>
.scriptManage {
  width: 100%;
  height: calc(100vh - 1.4rem);
}

.btn_group {
  // width: 100%;
  height: 1.2rem;
  line-height: 1.2rem;
  // border: 1px solid rgb(12, 15, 219);
  // margin-left: .4rem;
  margin-bottom: 0.2rem;
  // overflow: auto;
}

.btn_group_list {
  // width: 70%;
  height: 1.4rem !important;
  line-height: 1.4rem !important;
  // overflow: auto;
  // border: 2px solid red;
  font-size: 0.3rem;
  text-align: left;
  padding-left: 0.3rem;
  font-weight: 600;
}

.btn_group_btn {
  height: 1.4rem !important;
  line-height: 1.4rem !important;
  // border: 1px solid red;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  margin-left: 0.7rem;
}

.btn_group_btn1 {
  font-size: 0.26rem;
  // font-weight: 600;
  // margin: 0 auto;
}

.scriptManage_bottom {
  margin: 0 auto;
  margin-top: 0.3rem;
  width: 99.1%;
  height: calc(100vh - 1.6rem);
  display: flex;
  justify-content: space-between;
}

.scr_list {
  width: 20%;
  height: calc(100vh - 1.6rem);
  border: 1px solid #ccc;
  border-radius: 0.2rem;
  overflow: hidden;
  position: relative;
}

.headerTop {
  width: 100%;
  padding: 0 2%;
}

.top_list {
  // border: 1px solid red;
  height: calc(100% - 3.6rem);
  overflow: auto;
}

// 脚本列表的样式
.scr_list_top {
  width: 100%;
  height: 100%;
  // background-color: antiquewhite;
  overflow: auto;
  padding: 0 0.2rem;
}

.oneScriptList {
  width: 100%;
  height: 0.6rem;
  line-height: 0.6rem;
  padding: 0 2%;
  // text-align: left;
  display: flex;
  justify-content: space-between;
  font-size: 0.3rem;
  border-bottom: 1px dotted #666;
  cursor: pointer;
}

// 当前选中的脚本列表样式
.selectedItem {
  // background: linear-gradient(to right, #b5d0be, #8dbdb3);
  background-color: #eee;
}

// 按钮组
.left_btn_group {
  position: absolute;
  display: flex;
  bottom: 0.1rem;
  left: 50%;
  transform: translateX(-50%);
}

.scr_group {
  width: 58%;
  height: calc(100vh - 1.6rem);
  border: 1px solid #ccc;
  border-radius: 0.2rem;
  overflow: hidden;
  position: relative;
}

.point_group {
  width: 20%;
  height: calc(100vh - 1.6rem);
  border: 1px solid #ccc;
  border-radius: 0.2rem;
  overflow: auto;
}

.point_group h5 {
  width: 100%;
  font-size: 0.3rem;
  font-weight: normal;
  font-weight: 600;
  height: 0.8rem;
  line-height: 0.8rem;
  border-bottom: 1px solid #ccc;
  text-align: left;
  padding-left: 0.2rem;
}

.sensorTree {
  // min-height: 7rem;
  /* max-height: calc(100% - 5.6rem); */
  max-height: calc(100% - 1.2rem);
  box-sizing: border-box;
  border-radius: 5px;
  margin-top: 0.2rem;
  padding-top: 0.1rem;
  overflow: auto;
  color: #333;
  // border: 1px solid #ccc;
}

.sensorTree /deep/ .el-tree-node__content .el-tree-node__label {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.sensorTree /deep/ .el-tree-node__content .is-leaf {
  width: 0 !important;
  height: 0 !important;
  padding: 3px !important;
  overflow: hidden;
  /* padding-left:28px!important; */
}

.filter-tree {
  font-size: 0.3rem !important;
}

.filter-tree /deep/ .el-tree-node__content {
  width: 97% !important;
  // background-color: #61afef;
  // border: 1px solid red !important;
  // white-space: nowrap !important;
  // overflow: hidden !important;
  // text-overflow: ellipsis !important;
}

.filter-tree /deep/ .el-tree-node__content span:nth-child(2) {
  display: block;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.top_btn {
  display: inline-block;
  width: 2.2rem;
  height: 1.2rem;
  line-height: 1.2rem;
  user-select: none;
  margin-top: 0.1rem;
  background-color: #f56c6c;
  font-size: 0.3rem;
  border-radius: 0.2rem;
  text-align: center;
  color: #fff;
}

.inpu {
  width: 3rem;
}

.inpu /deep/ .el-input__inner {
  padding: 0 3px !important;
}

/* 其他的样式 */

.code-edit {
  height: calc(100% - 3.8rem);
  // border: 1px solid gray;
  // border-radius: .2rem;
  width: 100%;
  // margin-left: 1%;
  overflow: auto;
}

.code-edit /deep/ .CodeMirror {
  border-bottom: 1px solid #ccc;
}

.picker {
  height: 100% !important;
  text-align: left;
  width: 50%;
  margin: 0 auto;

  .code-edit {
    height: 100% !important;
    border-radius: 6px;
    border: 1px solid #e8e9eb;
    text-align: left !important;
  }
}

.code-edit /deep/.CodeMirror-scroll {
  text-align: left !important;
  overflow: auto !important;
  font-size: 0.38rem;
  height: 100% !important;
}

.code-edit /deep/.vue-codemirror {
  height: 100% !important;
  // border: 10px solid red !important;
}

.code-edit /deep/ .vue-codemirror .CodeMirror {
  height: 100% !important;
}

.top-title {
  background-color: #fafafa;
  height: 30px;
  vertical-align: center;
  line-height: 30px;
  padding-left: 10px;
  border-radius: 4px 4px 0 0;
  border-bottom: none;
}

.save_btn {
  position: absolute;
  left: 30px;
  bottom: 5px;
}

.code-edit /deep/ .CodeMirror {
  height: calc(100vh - 6.6rem) !important;

  /*表单变量样式*/
  .cm-field {
    background: #007bff;
    padding: 3px 5px;
    border-radius: 3px;
    color: #fff;
    margin: 0 1px;
  }

  /*函数样式*/
  .cm-func {
    font-weight: bold;
    color: #ae4597;
    line-height: 14px;
    margin: 0 1px;
    padding: 0 2px;
  }

  /*运算符的样式*/
  .cm-count {
    color: red;
  }

  .cm-green {
    color: green;
  }

  .cm-darkRed {
    color: #990000;
  }

  .cm-blue {
    color: blue;
  }

  .CodeMirror-scroll {
    width: 100%;
  }
}

.el-menu-demo {
  border-bottom: 0 !important;
  background-color: #f2f5f7;
}

.el-menu-demo /deep/ .el-submenu__title {
  border-bottom: 0 !important;
  font-size: 0.34rem !important;
  font-weight: 600;
}


.el-menu-demo /deep/ .is-opened {
  box-sizing: border-box;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

.el-menu-demo /deep/ .el-menu-item {
  color: black !important;
}

.itemMenu {
  color: #000 !important;
  background-color: #fff !important;
}

.itemMenu:hover {
  color: deepskyblue !important;
  // color:#fff !important;
  // background-color:deepskyblue !important;
}

.itemMenu.is-active {
  border-bottom: 0 !important;
  color: #fff !important;
  background-color: deepskyblue !important;
}

.el-menu-demo /deep/ .el-submenu__title:hover,
.oneMenu:hover {
  color: #fff !important;
  background-color: deepskyblue !important;
}

.oneMenu.is-active {
  border-bottom: 0 !important;
  color: #000 !important;
  background-color: #f2f5f7 !important;
}

.oneMenu.is-active:hover {
  color: #fff !important;
  background-color: deepskyblue !important;
}
</style>
